﻿using Core.Web.Api.DTO.User;
using IdentityModel;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;

namespace Core.Web.Api.Utils.HttpContextUser
{
    /// <summary>
    /// Http 用户Httpcontext
    /// </summary>
    public class HttpContextUser : IHttpContextUser
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        public HttpContextUser(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
        public IEnumerable<Claim> GetClaimsIdentity(string ClaimType)
        {
            if (_httpContextAccessor.HttpContext == null)
                throw new ArgumentNullException(nameof(IHttpContextAccessor));
            var jwtHandler = new JwtSecurityTokenHandler();
            if (!string.IsNullOrEmpty(GetToken()))
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(GetToken());

                return (from item in jwtToken.Claims
                        where item.Type == ClaimType
                        select item);
            }
            else
            {
                return new List<Claim>() { };
            }


        }

        public string GetToken()
        {
            if (_httpContextAccessor.HttpContext == null)
                throw new ArgumentNullException(nameof(IHttpContextAccessor));

            return _httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
        }

        public TokenUserDto GetUserInfo()
        {
            if (_httpContextAccessor.HttpContext == null)
                throw new ArgumentNullException(nameof(IHttpContextAccessor));

            if(!IsAuthenticated())//没有登录
            {
                return null;
            }
            if (!Guid.TryParse(GetClaimsIdentity(JwtClaimTypes.Id).FirstOrDefault()?.Value, out var IdGuid))
                throw new ArgumentException(nameof(JwtClaimTypes));

            if (!int.TryParse(GetClaimsIdentity(JwtClaimTypes.Role).FirstOrDefault()?.Value, out var Role))
                throw new ArgumentException("角色为空");

            return new TokenUserDto()
            {
                Id = IdGuid,
                Name = GetClaimsIdentity(JwtClaimTypes.Name).FirstOrDefault()?.Value ?? "",
                //Role = Enum.Parse<UserRole>(Role.ToString()),
                OpenId = GetClaimsIdentity(JwtClaimTypes.Profile).FirstOrDefault()?.Value ?? ""
            };

        }

        public List<string> GetUserInfoFromToken(string ClaimType)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            if (!string.IsNullOrEmpty(GetToken()))
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(GetToken());

                return (from item in jwtToken.Claims
                        where item.Type == ClaimType
                        select item.Value).ToList();
            }
            else
            {
                return new List<string>() { };
            }
        }

        public bool IsAuthenticated()
        {
            if (string.IsNullOrEmpty(GetToken()))
                return false;
            return true;
            //if (_httpContextAccessor.HttpContext == null)
            //    throw new ArgumentNullException(nameof(IHttpContextAccessor));
            //if (_httpContextAccessor.HttpContext.User.Identity == null)
            //    throw new ArgumentNullException(nameof(IIdentity));

            //return _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
        }
    }
}
